import { Component, Vue } from "vue-property-decorator";
import { FormulaService } from "@/services/formula-service";
import { ModalDialog } from "@/utils/modal-dialog.ts";
import "../../../public/marvinjs/js/marvinjslauncher.js";

@Component({
  props: {
    toolbar: {
      type: String,
      default: "reporting"
    },
    enableMolChange: {
      type: Boolean,
      default: false
    },
    format: {
      type: String,
      required: true
    },
    value: {
      type: String
    },
    index: {
      type: Number,
      required: true
    },
    minHeight: {
      type: String,
      default: "500"
    },
    minWidth: {
      type: String,
      default: "500"
    }
  },
  watch: {
    format: function() {
      this.createReaction();
    },
    value: function() {
      this.createReaction();
    }
  }
})
export class ReactionEditor extends Vue {
  async mounted() {
    this.createReaction();
  }

  createReaction() {
    window["MarvinJSUtil"].getEditor("#sketch" + this.$props.index).then(
      async sketcherInstance => {
        this.$emit("sketchChange", sketcherInstance);

        if (this.$props.enableMolChange) {
          // Add molchange event listener to update the binding property
          sketcherInstance.on("molchange", () => {
            sketcherInstance.exportStructure(this.$props.format).then(
              molsource => {
                this.$emit("onMolChange", molsource);
              },
              () => {}
            );
          });
        }

        // Show reaction
        if (this.$props.value) {
          const mrv = await FormulaService.convert(this.$props.format, "mrv", this.$props.value);
          sketcherInstance.importAsMrv(mrv);
        } else {
          sketcherInstance.importAsMrv(null);
        }
      },
      function(error) {
        ModalDialog.showError("notFound", error);
      }
    );
  }
}

export default ReactionEditor;
